var util = require('util');
var mongoose = require('mongoose');
var fs = require('fs');
var express = require('express');
var mongoStore = require('connect-mongodb');
var TaskManager = require('./TaskManager');

/**
 * 
 * Module for interfacing with embeded TCP/IP hardware controller/sensors.
 * Includes a web GUI user interface, periodic task manager, MongoDB connection,
 * and device access methods
 * 
 * @class Server
 * @author jmanero
 * 
 * @requires util
 * 
 * @requires TaskManager
 * @requires ModelManager
 * @requires ViewController
 * 
 * @constructor
 * @param {Function}
 *            callback
 * 
 */
server = function(callback) {
	// Start up the MongoDB driver (Mongoose), and connect
	model = {};
	connection = mongoose.createConnection('mongodb://127.0.0.1/Control');

	// Load and start the logger
	require('./Models/Message');
	model.Message.startup(2, true);
	
	// Log connection errors
	connection.on('error', function(e) {
		model.Message.fuck(e);
	});
	
	// Wait for the connection to be open before doing stuff
	connection.on('open', function() {
//		model.Message.log('Info', "THE CONNECTION IS FUCKING OPEN");
		
		// Import a few more models
		require('./Models/Device');
		require('./Models/Port');

		// and start them
		model.Device.startup();
		model.Port.startup();
		
		/**
		 * Manage periodic daemon tasks
		 * 
		 * @type TaskManager
		 * @memberOf Server
		 */
		server.taskManager = new TaskManager(function() {
			this.on('DeviceLocate', function() {
				model.Device.locate();
			});

			this.on('DeviceSync', function() {
				model.Device.sync();
			});

			this.addEmitter('DeviceLocate', 7010);
			this.addEmitter('DeviceSync', 1000);
		});

		app = express

		callback(server);
		model.Message.info("Started ControlServer");
	});

	return this;
};

exports.createServer = server;
